/**
 * 自定义 XML 解析工具类
 * 不使用浏览器或 Node.js 环境下的方法
 */
export class XmlParser {
    private xmlString: string;
    private position: number = 0;
    private currentChar: string | null = null;

    constructor(xmlString: string) {
        // this.xmlString = xmlString;
		this.xmlString = xmlString.replace(/<!--[\s\S]*?-->/g, '');
        this.position = 0;
        this.currentChar = this.xmlString[0] || null;
    }

    /**
     * 解析整个 XML 文档
     */
    public parse(): any {
        this.skipWhitespace();
        return this.parseElement();
    }

    /**
     * 前进到下一个字符
     */
    private advance(): void {
        this.position++;
        this.currentChar = this.position < this.xmlString.length ? 
            this.xmlString[this.position] : null;
    }


    private isFinished(): boolean {
        return this.position>=this.xmlString.length;
    }

    /**
     * 跳过空白字符
     */
    private skipWhitespace(): void {
        while (this.currentChar !== null && this.isWhitespace(this.currentChar)) {
            this.advance();
        }
    }

    /**
     * 检查字符是否为空白
     */
    private isWhitespace(char: string): boolean {
        return char === ' ' || char === '\t' || char === '\n' || char === '\r';
    }

    /**
     * 解析 XML 元素
     */
    private parseElement(): any {
        if (this.currentChar !== '<') {
            throw new Error('Expected < at position ' + this.position);
        }

        // debugger
        this.advance(); // 跳过 '<'
        const tagName = this.parseTagName();
		console.log("tagName",tagName)
        const attributes = this.parseAttributes();
        let textContent = '';
        const children: any[] = [];

        // 处理自闭合标签
        if (this.currentChar === '/') {
            this.advance(); // 跳过 '/'
            if (this.currentChar !== '>') {
                throw new Error('Expected > at position ' + this.position);
            }
            this.advance(); // 跳过 '>'
            return { tagName, attributes };
        }

        if (this.currentChar !== '>') {
            throw new Error('Expected > at position ' + this.position);
        }
        this.advance(); // 跳过 '>'

        // 解析元素内容
        while (this.currentChar !== null && this.currentChar !== '<') {
            textContent += this.currentChar;
            this.advance();
        }

        // 去除多余空白
        textContent = textContent.trim();


        // 解析子元素
        while (this.currentChar === '<') {
            // debugger
            if (this.peek() === '/') {
                // 结束标签
                this.advance(); // 跳过 '<'
                this.advance(); // 跳过 '/'
                const closingTag = this.parseTagName();
                if (closingTag !== tagName) {
                    throw new Error(`Mismatched closing tag: expected ${tagName}, found ${closingTag}`);
                }
                if (this.currentChar !== '>') {
                    throw new Error('Expected > at position ' + this.position);
                }
                this.advance(); // 跳过 '>'
                break;
            } else {
                // 子元素
                children.push(this.parseElement());

                
                while (this.isWhitespace(this.currentChar) && !this.isFinished()) {
                    this.advance();
                }
            }
        }

        return {
            tagName,
            attributes,
            textContent,
            children: children.length > 0 ? children : undefined
        };
    }

    /**
     * 解析标签名称
     */
    private parseTagName(): string {
        let tagName = '';
        while (this.currentChar !== null && !this.isWhitespace(this.currentChar) && 
               this.currentChar !== '>' && this.currentChar !== '/') {
            tagName += this.currentChar;
            this.advance();
        }
        return tagName;
    }

    /**
     * 解析属性
     */
    private parseAttributes(): Record<string, string> {
        const attributes: Record<string, string> = {};
        
        while (this.currentChar !== null && this.currentChar !== '>' && this.currentChar !== '/') {
            this.skipWhitespace();
            if (this.currentChar === '>' || this.currentChar === '/') break;
            
            const name = this.parseAttributeName();
            if (this.currentChar !== '=') {
                throw new Error('Expected = at position ' + this.position);
            }
            this.advance(); // 跳过 '='
            
            const quote = this.currentChar;
            if (quote !== '"' && quote !== "'") {
                throw new Error('Expected quote at position ' + this.position);
            }
            this.advance(); // 跳过引号
            
            let value = this.parseAttributeValue(quote);

            
            if (value == "false") {
                value = false;
            }
            if (value == "true") {
                value = true;
            }


            if (!isNaN(parseFloat(value)) && !isNaN(value)) {
                value = parseFloat(value)
            }
              


            attributes[name] = value;
            
            if (this.currentChar !== quote) {
                throw new Error('Expected closing quote at position ' + this.position);
            }
            this.advance(); // 跳过结束引号
        }
        
        return attributes;
    }

    /**
     * 解析属性名称
     */
    private parseAttributeName(): string {
        let name = '';
        while (this.currentChar !== null && !this.isWhitespace(this.currentChar) && 
               this.currentChar !== '=' && this.currentChar !== '>' && this.currentChar !== '/') {
            name += this.currentChar;
            this.advance();
        }
        return name;
    }

    /**
     * 解析属性值
     */
    private parseAttributeValue(quote: string): string {
        let value = '';
        while (this.currentChar !== null && this.currentChar !== quote) {
            value += this.currentChar;
            this.advance();
        }
        return value;
    }

    /**
     * 查看下一个字符但不前进
     */
    private peek(): string | null {
        return this.position + 1 < this.xmlString.length ? 
            this.xmlString[this.position + 1] : null;
    }
}

// // 使用示例
// const xmlString = `<vitalsign>
//     <!-- 尺寸定义 -->
//     <vitalsize width="192.4" height="251" symbol="mm" print-color="false" noSplit="false" circle="1.8" printPadding="12" printZoom="0.94" cx="4"/>
//     <vitalreact left="24" top="0" width="167.0" height="244"/>
//     <!--页眉-->
//     <vitalheader show="false" print-show="true" innerHtml="页眉内容"/>
//     <!--页脚-->
//     <vitalfooter show="true" print-show="true" innerHtml="页脚内容"/>
//     <!-- 显示项配置 -->
//     <vitalshows>
//         <vitalshow name="时间" timepoint="[2,8,10,14,18,22]" columnsInDay="6" newLine="0" lineCount="0" spaceMark="|" splitType="1"/>
//         <vitalshow name="呼吸" columnsInDay="6" newLine="0" lineCount="0" spaceMark="|" splitType="undefined"/>
//     </vitalshows>
//     <!-- 线条配置 -->
//     <vitalpens>
//         <vitalpen id="0" color="255,0,0,1" pen-width="1"/>
//         <vitalpen id="1" color="0,0,0,1" pen-width="1"/>
//     </vitalpens>
//     <!-- 字体配置 -->
//     <vitalfonts>
//         <vitalfont id="1" font-name="宋体" font-size="10" font-bold="false" font-underline="false" font-inital="false" text-color="0,0,0,1"/>
//         <vitalfont id="2" font-name="宋体" font-size="12" font-bold="false" font-underline="false" font-inital="false" text-color="255,0,0,1"/>
//     </vitalfonts>
//     <!-- 符号配置 -->
//     <vitalsymbols>
//         <vitalsymbol id="1" symbol1="●" symbol2="" symbol3="" color="0,0,255,1" font-name="宋体" font-size="15" font-bold="false"/>
//         <vitalsymbol id="2" symbol1="✖" symbol2="" symbol3="" color="0,0,255,1" font-name="宋体" font-size="13" font-bold="false"/>
//     </vitalsymbols>
// </vitalsign>`;
